package com.dlxj.service.impl;

import java.util.List;

import com.dlxj.dao.BaseDAO;
import com.dlxj.entity.Group;
import com.dlxj.entity.Purview;
import com.dlxj.service.GroupService;
import com.dlxj.util.ConstClass;

public class GroupServiceImpl implements GroupService {

	BaseDAO baseDAO;

	@Override
	public int addGroup(Group group) {
		int count = count(group);
		if (count > 0) {
			return ConstClass.ADD_FAILURE;
		}
		baseDAO.save(group);
		return ConstClass.ADD_SUCCESS;
	}

	@Override
	public int modifyGroupPurview(int gid, Purview purview) {
		Group group = (Group) baseDAO.findById(Group.class, gid);
		group.setPurview(purview);
		baseDAO.update(group);
		return ConstClass.UPDATE_SUCCESS;
	}

	@Override
	public int deleteGroup(int gid) {
		int count = baseDAO.countHql(
				"select count(*) from User where group.id = ?",
				new Object[] { gid });
		if (count > 0) {
			return ConstClass.DELETE_FAILURE;
		}
		baseDAO.delete(Group.class, gid);

		return ConstClass.DELETE_SUCCESS;
	}

	@Override
	public int modifyGroupName(int gid, String name) {
		Group group = (Group) baseDAO.findById(Group.class, gid);
		int count = count(name);
		if (count > 0) {
			return ConstClass.UPDATE_FAILURE;
		}
		group.setName(name);
		baseDAO.update(group);
		return ConstClass.UPDATE_SUCCESS;
	}

	@Override
	public int modifyGroupState(int gid, int state) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<Group> findGroupList() {
		List<Group> groups = (List<Group>) baseDAO.findByHql("from Group");
		for (Group group : groups) {
			int count = baseDAO.countHql(
					"select count(*) from User where group.id = ?",
					new Object[] { group.getId() });
			group.setUserCount(count);
		}
		return groups;
	}

	public BaseDAO getBaseDAO() {
		return baseDAO;
	}

	public void setBaseDAO(BaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}

	private int count(Group group) {
		return baseDAO.countHql("select count(*) from Group where name = ?",
				new Object[] { group.getName() });
	}

	private int count(String name) {
		return baseDAO.countHql("select count(*) from Group where name = ?",
				new Object[] { name });
	}

	@Override
	public List<Object[]> bing() {
		return baseDAO
				.findByHql("SELECT g.name,COUNT(u)  FROM User u inner JOIN u.group g GROUP BY g.name");
	}

}
